package cn.tedu.serviceEdu.service.impl;

import cn.tedu.serviceEdu.entity.EduSubject;
import cn.tedu.serviceEdu.entity.excel.SubjectData;
import cn.tedu.serviceEdu.listener.SubjectExcelListener;
import cn.tedu.serviceEdu.mapper.EduSubjectMapper;
import cn.tedu.serviceEdu.service.EduSubjectService;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author hong
 * @since 2023-05-17
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {



    @Override
    public void saveObject(MultipartFile file,EduSubjectService subjectService) {
        try {
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, SubjectData.class,new SubjectExcelListener(subjectService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<EduSubject> getSubjectTree(List<EduSubject> list) {

        // 2 处理数据 父子关系
        List<EduSubject> resultList = new ArrayList<>();
        Map<String,EduSubject> cacheMap = new HashMap<>();

        list.forEach( eduSubject -> {
            // 3.1 获得父分类
            eduSubject.setLabel(eduSubject.getTitle());
            EduSubject parenEduSubject = cacheMap.get(eduSubject.getParentId());
            // 3.2 如果没有父添加到resultList中，如果有父追加父内部
            if(parenEduSubject == null) {
                resultList.add(eduSubject);
            } else {
                parenEduSubject.getChildren().add(eduSubject);
            }

            // 3.3 缓存自己
            cacheMap.put(eduSubject.getId() , eduSubject);

        });
        return resultList;
    }

}
